package com.zkingsoft.plugin.util.wx;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

public class AccessToken
{

  private static AccessToken accessToken = null;
  private String access_token;
  private static long endTime;

  public static String getAccessToken()
  {
    if (accessToken == null) {
      accessToken = new AccessToken();
      accessToken.makeAccessToken();
    }

    accessToken.access_token = accessToken.makeAccessToken();

    return accessToken.access_token;
  }

  private String makeAccessToken()
  {
    HttpRequest request = new HttpRequest();

    Map<String,String> params = new HashMap<String,String>();
    params.put("grant_type", "client_credential");
    params.put("appid", Constants.APPID);
    params.put("secret", Constants.APPSECRET);
    HttpResponse result = null;
    try
    {
      result = request.sendHttpsGet("https://api.weixin.qq.com/cgi-bin/token", params);
    }
    catch (IOException localIOException) {
    }
    endTime = System.currentTimeMillis() + 7100000L;
    JSONObject json = JSONObject.fromObject(result.getDataString());
    System.out.println("access_token:" + json.getString("access_token"));
    return json.getString("access_token");
  }

  public static void setAppInfo(String appid, String appsecret)
  {
	Constants.APPID = appid;
	Constants.APPSECRET = appsecret;
    if (accessToken == null) {
      accessToken = new AccessToken();
    }
    accessToken.makeAccessToken();
  }
}
